package taskrunner

import (
	"github.com/pkg/errors"
	"log"
	"os"
	"sync"
	"video_server/scheduler/dbops"
	"video_server/scheduler/ossops"
)

func DeleteVideo(vid string)error{
	err := os.Remove(VIDEO_PATH + vid)
	if err != nil && !os.IsNotExist(err) {
		log.Printf("deleting video error : %v",err)
	}

	ossfn := "/videos/"+ vid
	bn := "avenssi-vedeos2"
	ok := ossops.DeleteObject(ossfn,bn)
	if !ok {
		log.Printf("Deleting video err")
		return errors.New("Deleting video err" )
	}
	return nil
}



func VideoClearDispatcher(dc dataChan)error{
	res,err := dbops.ReadVideoDeletionRecord(3)
	if err !=nil{
		log.Printf("video clear dispatcher error : %v",err)
		return err
	}
	if len(res) == 0{
		return errors.New("All tasks finished")
	}

	for _,id := range res{
		dc <-id
	}
	return nil
}

func VideoClearExecutor (dc dataChan)error{

	errMap := &sync.Map{}
	var err error
	forloop:
		for  {
			select {
			case vid := <-dc:
				//有可能会重复读取id，但是最终都能删掉
				go func(id interface{}){
					if err := DeleteVideo(id.(string));err != nil{
						errMap.Store(id,err)
						return
					}
					if err := dbops.DelVideoDeletionRecord(id.(string));err != nil {
						errMap.Store(id,err)
						return
					}
				}(vid)
			default:
				break forloop
			}
		}

	errMap.Range(func(key, value interface{}) bool {
		err = value.(error)
		if err != nil {
			return false
		}
		return true
	})

	return err
}